<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>

        <template #right>
          <!--  v-if="hasPonitPermission('excel_import')" -->
          <el-button
            v-permission="'excel_import'"
            type="warning"
            size="small"
            @click="$router.push('/import?type=user')"
          >excel导入</el-button>
          <!--  v-if="hasPonitPermission('excel_export')" -->
          <el-button
            v-permission="'excel_export'"
            type="danger"
            size="small"
            @click="exportExcel"
          >excel导出</el-button>
          <!--  v-if="hasPonitPermission('p-em-add')" -->
          <el-button
            v-permission="'p-em-add'"
            type="primary"
            size="small"
            @click="openEmployeeFn"
          >新增员工</el-button>
        </template>
      </page-tools>

      <el-card
        v-loading="isLoading"
        style="margin-top: 10px;"
      >
        <el-table
          border
          :data="employeeList"
        >
          <el-table-column
            label="序号"
            type="index"
            :index="indexMethod"
          />
          <el-table-column
            label="姓名"
            prop="username"
          />
          <el-table-column label="头像">
            <template #default="{row}">
              <img
                v-imgerror="defaultImag"
                class="staff"
                :src="row.staffPhoto || nullDefault"
              >
            </template>
          </el-table-column>
          <el-table-column
            label="手机号"
            prop="mobile"
          />
          <el-table-column
            label="工号"
            prop="workNumber"
          />
          <el-table-column
            label="聘用形式"
            prop="formOfEmployment"
            :formatter="formateData"
          />
          <el-table-column
            label="部门"
            prop="departmentName"
          />
          <el-table-column
            label="入职时间"
            prop="timeOfEntry"
          >
            <template #default="{row}">
              {{ formatTime(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            fixed="right"
            width="280"
          >
            <template #default="{row}">
              <!--  v-if="hasPonitPermission('p-em-look')" -->
              <el-button
                v-permission="'p-em-look'"
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <!--  v-if="hasPonitPermission('assign_role')" -->
              <el-button
                v-permission="'assign_role'"
                type="text"
                size="small"
                @click="assignRoleClick(row.id)"
              >分配角色</el-button>
              <!--  v-if="hasPonitPermission('emp_delete')" -->
              <el-button
                v-permission="'p-em-del'"
                type="text"
                size="small"
                @click="delEmplyees(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :total="total"
            :current-page="page"
            :page-size="size"
            :page-sizes="[5,10,20,30]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
      <addEmployee :show-dialog.sync="showDialog" />
      <assginRole
        :show-role-dialog.sync="showRoleDialog"
        :user-id="userId"
      />
    </div>
  </div>
</template>

<script>
import { getEmployeesListApi, delEmployeesApi } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import dayjs from 'dayjs'
import AddEmployee from './components/add-employee.vue'
import avatar from '@/assets/common/bigUserHeader.png'
import assginRole from './components/assign-role.vue'
// import permission from '@/mixins/permission'
// import mixins from '@/mixins/permission'
// 使用mixins的方式：
// 1.先导入mixins所在的文件
// 2.把mixins混入当前组件
export default {
  name: 'Employees',
  components: {
    AddEmployee,
    assginRole
  },
  // mixins: [permission],
  data() {
    return {
      page: 1,
      size: 10,
      employeeList: [],
      total: 0,
      isLoading: false,
      showDialog: false,
      defaultImag: avatar,
      nullDefault: 'https://hrsass-lpp-1315196096.cos.ap-beijing.myqcloud.com/16690208584421.jpg',
      showRoleDialog: false,
      userId: ''
    }
  },

  created() {
    this.getEmployeesList()
  },
  methods: {
    assignRoleClick(id) {
      this.showRoleDialog = true
      this.userId = id
    },
    async exportExcel() {
      const {
        data: { rows }
      } = await getEmployeesListApi(1, this.total)
      // console.log(rows)
      const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      // 跨列合并
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
      // 跨行合并
      const merges = ['A1:A2', 'B1:F1', 'G1:G2']
      const headersRelations = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      const data = this.formateData2Arr(headersArr, rows, headersRelations)
      // 触发方法的时候导入包
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: headersArr, // excel的表头
          data: data, // 导出的数据必须是一个二维数组
          filename: '员工信息', // 导出的文件名
          autoWidth: true, // 单元格宽度是否自适应
          bookType: 'xlsx', // 文件的后缀名
          multiHeader,
          merges
        })
      })
    },
    formateData2Arr(headersArr, rows, headersRelations) {
      const arr = []
      rows.forEach(item => {
        const tempArray = []
        headersArr.forEach(key => {
          const englishKey = headersRelations[key]
          let value = item[englishKey]
          if (englishKey === 'formOfEmployment') {
            const hireObj = EmployeeEnum.hireType.find(item => item.id === Number(value))
            value = hireObj ? hireObj.value : '未知'
          }
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            value = this.formatTime(value)
          }
          tempArray.push(value)
        })
        arr.push(tempArray)
      })
      return arr
    },
    openEmployeeFn() {
      this.showDialog = true
    },
    delEmplyees(id) {
      this.$confirm('您确定要删除吗', '温馨提示')
        .then(async() => {
          await delEmployeesApi(id)
          if (this.page > 1 && this.employeeList.length === 1) {
            this.page--
          }
          this.$message.success('删除成功')
          this.getEmployeesList()
        })
        .catch(() => {})
    },
    // cellVale当前聘用形式对应的值
    formateData(row, column, cellValue, index) {
      // console.log(row, column, cellValue, index)
      // 正式 id=1  非正式 id=2
      // if (cellValue === 1) {
      //   return '正式'
      // }
      // if (cellValue === 2) {
      //   return '非正式'
      // }
      // hireType是聘用形式
      const hireObj = EmployeeEnum.hireType.find(item => item.id === cellValue)
      return hireObj ? hireObj.value : '未知'
    },
    formatTime(time) {
      return dayjs(time).format('YYYY-MM-DD')
    },
    async getEmployeesList() {
      this.isLoading = true
      const { data } = await getEmployeesListApi(this.page, this.size)
      // 员工列表
      this.employeeList = data.rows
      // 页码总数
      this.total = data.total
      this.isLoading = false
    },
    indexMethod(index) {
      return (this.page - 1) * this.size + index + 1
    },
    // 页容量改变
    handleSizeChange(val) {
      this.size = val
      this.getEmployeesList()
    },
    // 页码改变
    handleCurrentChange(val) {
      this.page = val
      this.getEmployeesList()
    }
  }
}
</script>

<style lang="scss" scoped>
.employees-container {
  .staff {
    width: 70px;
    height: 70px;
    border-radius: 50%;
  }
}
</style>
